package com.bc.trade.vo;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.bc.common.message.BaseReq;
import com.bc.trade.model.RiskRule;
import com.bc.trade.model.TradeOrder;
import com.fs.common.util.FSDate;
import com.jfinal.kit.StrKit;

public class RiskRuleCheck {

	private Integer amount;
	private String payType;
	private BaseReq req;
	private RiskRule rule;

	public RiskRuleCheck(Integer amount, String payType, BaseReq req, RiskRule rule) {
		this.req = req;
		this.rule = rule;
		this.amount = amount;
		this.payType = payType;
	}

	public String check() {
		// 单笔限额验证
		if (rule.getSingleLimit() != null && rule.getSingleLimit() > 0) {
			if (amount.intValue() > rule.getSingleLimit().intValue()) {
				return "该笔交易金额已大于系统设置的单笔交易限额.";
			}
		}

		// 日限额验证
		if (rule.getDayLimit() != null && rule.getDayLimit() > 0) {
			Long sumAmount = TradeOrder.dao.sumOrderAmount(req.getMerchCode(), FSDate.getDate());
			sumAmount = sumAmount + amount;
			if (sumAmount != null && (sumAmount.intValue() > rule.getDayLimit().intValue())) {
				return "今日交易金额已大于系统设置的当日总交易限额";
			}
		}

		// 支付类别限额验证
		if (rule.getPayTypeDayLimit() != null && rule.getPayTypeDayLimit() > 0) {
			Long sumPayTypeAmount = TradeOrder.dao.sumPayTypeAmount(req.getMerchCode(), payType, FSDate.getDate());
			sumPayTypeAmount = sumPayTypeAmount + amount;
			if (sumPayTypeAmount != null && (sumPayTypeAmount.intValue() > rule.getPayTypeDayLimit().intValue())) {
				return "今日该支付类别交易总额已大于系统设置的支付类别总交易限额";
			}
		}

		// 总交易金额限额验证
		if (rule.getSumLimit() != null && rule.getSumLimit() > 0) {
			Long sumLimit = TradeOrder.dao.sumAmount(req.getMerchCode());
			sumLimit = sumLimit + amount;
			if (sumLimit != null && (sumLimit > rule.getSumLimit())) {
				return "此商户总交易金额已大于系统设置的总交易限额";
			}
		}

		int currentTime = minTimeToInt(new SimpleDateFormat("HH:mm").format(new Date()));
		// 交易时间范围验证
		if (StrKit.notBlank(rule.getTradeStartTime())) {
			if (currentTime < minTimeToInt(rule.getTradeStartTime())) {
				return "非交易时间范围，不能发起交易";
			}
		}

		// 交易时间范围验证
		if (StrKit.notBlank(rule.getTradeEndTime())) {
			if (currentTime > minTimeToInt(rule.getTradeEndTime())) {
				return "非交易时间范围，不能发起交易";
			}
		}

		return null;
	}

	private static int minTimeToInt(String src) {
		src = src.replaceAll(":", "");
		return Integer.parseInt(src);
	}

}
